package com.yj.netty.chapter02;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {

    public static void main(String[] args) {

        NioEventLoopGroup work = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(work)

               .channel(NioSocketChannel.class)
               .handler(new ChannelInitializer<SocketChannel>() {
                   @Override
                   protected void initChannel(SocketChannel socketChannel) throws Exception {
                       socketChannel.pipeline().addLast(new StringDecoder());
                       socketChannel.pipeline().addLast(new StringEncoder());
                       socketChannel.pipeline().addLast(new NettyClientHandler());
                   }
               });

        try{
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8080).sync().channel().closeFuture().sync();
            future.addListener(future1 -> {
               if (future1.isSuccess()){
                   System.out.println("连接成功");
               }else{
                   System.out.println("连接失败");
               }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
